package com.oman.metadata;

import java.lang.reflect.Field;
import java.util.Formatter;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.oman.R;

public class MediaMetaData extends Activity{
    private final String TAG = "MediaMetaData";
    private String filePath = null;
    ImageView capturedImageView;
    TextView mTimeView;
    SeekBar mSeekBar;
    private MediaMetadataRetriever mediaMetadataRetriever;
    private int mTotalDuration;

    private FrameTask mthumbTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d(TAG, "==> onCreate");
        /* Resolve the intent */
        Intent intent = getIntent();
        if (intent != null) {
            Uri uri = (Uri) intent.getParcelableExtra("uri");
            if (uri != null) {
                Log.d(TAG, "The Input Uri = " + uri.getPath());
                filePath = uri.getPath();
                Log.d(TAG, "Input filepath " + filePath);
            } else {
                Toast.makeText(getApplicationContext(), "Input Uri is null", Toast.LENGTH_LONG).show();
                return;
            }
        } else {
            Log.e(TAG, "intent is null");
            Toast.makeText(getApplicationContext(), "intent is null", Toast.LENGTH_LONG).show();
            return;
        }

        setContentView(R.layout.mediametadata_activity);
        capturedImageView = (ImageView) findViewById(R.id.full_image);
        mTimeView = (TextView) findViewById(R.id.timeTextView);
        mSeekBar = (SeekBar) findViewById(R.id.seekBar);
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                Log.d(TAG, "onProgressChanged progress="+progress);
                int rate = (progress * mTotalDuration)/100;
                mTimeView.setText(stringForTime(rate));
//                Bitmap bmFrame = mediaMetadataRetriever.getFrameAtTime(rate * 1000); // unit in microsecond
//                Bitmap bmFrame = mediaMetadataRetriever.getFrameAtTime(rate * 1000, MediaMetadataRetriever.OPTION_CLOSEST);
//                Bitmap bmFrame = mediaMetadataRetriever.getFrameAtTime(rate * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
//                capturedImageView.setImageBitmap(bmFrame);
//                if(mthumbTask != null) {
////                    mthumbTask = new getThumnailTask(capturedImageView, mediaMetadataRetriever);
                Log.e(TAG, "mthumbTask staus" + mthumbTask.getStatus());
//                if(mthumbTask.getStatus() =Status.FINISHED);
//                    mthumbTask.execute(progress);
//                }
            }
        });
    }

    @Override
    protected void onResume() {
        Log.d(TAG, "==> onResume");
        super.onResume();

        mediaMetadataRetriever = new MediaMetadataRetriever();
        if (mediaMetadataRetriever != null) {
            try {
                Class<?> cMediaMetadataRetriever = Class.forName("android.media.MediaMetadataRetriever");
                Field rotation = cMediaMetadataRetriever.getDeclaredField("METADATA_KEY_VIDEO_ROTATION");

                mediaMetadataRetriever.setDataSource(filePath);
                String meta = mediaMetadataRetriever.extractMetadata(rotation.getInt(null));

//                mVideoRotation = Integer.parseInt(meta);
            } catch (NumberFormatException e) {
                Log.w(TAG, "Integer.parseInt() NumberFormatException");
            } catch (ClassNotFoundException e) {
                Log.w(TAG, "Class.forName() ClassNotFoundException");
            } catch (NoSuchFieldException ex) {
                Log.w(TAG, "Class.getDeclaredField() NoSuchFieldException");
            } catch (IllegalArgumentException ex) {
                Log.w(TAG, "Field.getInt IllegalArgumentException");
            } catch (IllegalAccessException ex) {
                Log.w(TAG, "Field.getInt IllegalAccessException");
            } catch(RuntimeException e) {
                Log.e(TAG, "RuntimeException");
//                returnToInvoker();
                return;
            }

//            if      (mVideoRotation == 1) { mVideoRotation =  90; }
//            else if (mVideoRotation == 2) { mVideoRotation = 180; }
//            else if (mVideoRotation == 3) { mVideoRotation = 270; }

            String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            try {
                mTotalDuration = Integer.parseInt(duration);
            } catch (NumberFormatException e) {
                Log.w(TAG, "Integer.parseInt() NumberFormatException");
            }
        }


        mediaMetadataRetriever.setDataSource(filePath);
        Bitmap bmFrame = mediaMetadataRetriever.getFrameAtTime(0 * 1000); // unit in microsecond
        capturedImageView.setImageBitmap(bmFrame);
//        mediaMetadataRetriever.release();
        mthumbTask = new FrameTask(capturedImageView, mediaMetadataRetriever);
//        for(int count = 0; count <10 ; count++) {
//            mthumbTask.execute(10+count);
//            try {
//                Thread.sleep(200);
//            } catch (InterruptedException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//        }
        mthumbTask.execute(30);

    }

    @Override
    protected void onPause() {
        Log.d(TAG, "==> onPause");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "==> onDestroy");
        super.onDestroy();
    }
    private String stringForTime(int timeMs) {
        if (timeMs < 0) {
            return "";
        }
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours   = totalSeconds / 3600;

        StringBuilder mFormatBuilder = new StringBuilder();
        Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

        mFormatBuilder.setLength(0);
        return mFormatter.format("%02d:%02d:%02d", hours, minutes, seconds).toString();
    }

}
